#include "../include/thread_pool.h"
#include "../include/net_connection.h"

/* Usage: 服务器主程序  */

// 进程间通信管道
int exitPipe[2]; 
void handler(int signum) {
    printf("signum = %d\n", signum);
    write(exitPipe[1], "1", 1);
}

int main(int argc, char *argv[]){
    pipe(exitPipe);
    if (fork()) {
        // 父进程
        close(exitPipe[0]);
        /* signal(SIGUSR1, handler); */
        signal(SIGPIPE, handler);
        wait(NULL);
        printf("Server is going to exit!\n");
        exit(0);
    }
    // 子进程 线程池
    close(exitPipe[1]);
    // ../conf/server.conf
    ARGS_CHECK(argc, 2);
    char ip[20] = {0};
    char port[10] = {0};
    int workernum = 0;
    get_server_conf(argv[1], ip, port, &workernum);
    printf("server ip: %s\n", ip);
    printf("server port: %s\n", port);
    printf("thread num: %d\n", workernum);

    sharedRes_t sharedRes;
    shared_res_init(&sharedRes, workernum);
    threadPool_t threadPool;
    thread_pool_init(&threadPool, workernum);
    // 创建线程池
    make_worker(&sharedRes, &threadPool);
    // 网络
    int sockfd = tcp_init(ip, port);
    int epfd = epoll_create(10);
    epoll_add(epfd, sockfd);
    epoll_add(epfd, exitPipe[0]);
    struct epoll_event readySet[1024] = {0};
    while (1) {
        int readynum = epoll_wait(epfd, readySet, 1024, -1);
        for (int i = 0; i < readynum; i++) {
            if (readySet[i].data.fd == sockfd) {
                int fd_client = accept(sockfd, NULL, NULL);
                printf("fd_client = %d\n", fd_client);
                // 加锁生产
                pthread_mutex_lock(&sharedRes.mutex);
                en_queue(&sharedRes.taskQueue, fd_client);
                pthread_cond_broadcast(&sharedRes.cond);
                pthread_mutex_unlock(&sharedRes.mutex);
                // 交给worker关fd_client
            }   
            else if (readySet[i].data.fd == exitPipe[0]) {
                printf("ThreadPool is going to exit!\n");
                pthread_mutex_lock(&sharedRes.mutex);
                sharedRes.exitFlag = 1;
                pthread_cond_broadcast(&sharedRes.cond);
                pthread_mutex_unlock(&sharedRes.mutex);
                for(int j = 0; j < workernum; ++j){
                    pthread_join(threadPool.tidArr[j], NULL);
                }   
                printf("Master is going to exit!\n");
                exit(0);
            }   
        }   
    }   

    return 0;
}

